import axios from 'axios'
import Router from '../../router'
// import store from '@store'

// const tokenKey = 'x-auth-token' 
const tokenKey = 'Authorization'

const BASE_URL = {
    development: 'http://172.31.20.141:82/',
    test: 'http://172.31.20.141:82/',
    test2: 'http://172.31.20.141:84/',
    production: 'http://172.31.20.141:81/'
}


export const uploadFile = (file, url) => {
    const param = new FormData()
    param.append("file", file)

    const config = {
        headers: {
            "Content-Type": "multipart/form-data"
        }
    }

    return axios.post(BASE_URL[process.env.NODE_ENV] + url, param, config).then(res => res)
}

export const createService = (baseUrl,tokenK=tokenKey) => {
    const service = axios.create({
        baseURL: baseUrl[process.env.NODE_ENV],
        headers: {
            //'Cache-Control': 'no-cache',//不缓存
            'Content-Type': 'application/json;charset=UTF-8'
        },
        timeout: 20000
    })

    service.interceptors.request.use(
        config => {
            if (localStorage.getItem("token") && tokenK==='Authorization') {
                config.headers[tokenK] = localStorage.getItem("token")
                // config.headers['x-auth-token'] = localStorage.getItem("token")
            }
            if(localStorage.getItem("token_ticket") && tokenK==='x-auth-token'){
                config.headers[tokenK] = localStorage.getItem("token_ticket")
            }
            return config
        },
        error => {
            Promise.reject(error)
        }
    )

    service.interceptors.response.use(
        response => {
            if (response.status === 200) {
                if (response.data && (response.data.status === true || response.data.success)) {
                    return Promise.resolve(response.data.data)
                }
                if (response.data.error && (response.data.error.code == 1002 || response.data.error.code == 1001)) {
                    Router.replace(
                        `/error?msg=${response.data.error.msg}请重新打开应用`
                    );
                    return Promise.reject({
                        message: response.data.msg,
                        data: response.data
                    })
                }
                return Promise.reject({
                    message: response.data.msg || response.data.message,
                    data: response.data
                })
            }
            return Promise.reject({
                message: '出错了'
            })
        },
        error => {
            return Promise.reject(error.response.data)
        }
    )

    return service
}

export default createService(BASE_URL)